<?php

namespace App\Http\Controllers\Network;

use App\Http\Controllers\Controller;
use App\Models\AdminUserModel;
use App\Models\yb\GoodsModel;
use App\Models\yb\GoodsTypeModel;
use App\Models\yb\NetworkCreditRecordModel;
use App\Models\yb\NetworkGoodsModel;
use App\Models\yb\NetworkGoodsOrderModel;
use App\Models\yb\NetworkGoodsOrderDetailModel;
use App\Models\yb\NetworkCreditRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Factory;




class GoodsController extends Controller
{

    /**
     * Get a JWT via given credentials.
     *  商品列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function GoodsListing(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $network_goods = NetworkGoodsModel::where(['network_id'=>$user_data['id'],'status'=>1])->orderBy('weight','desc')->skip(($page - 1) * $take)->take($take)->get();
        $data = array();
        foreach($network_goods as $key=>$val){

            $goods_data = GoodsModel::where(['id'=>$val['goods_id']])->first();
            $goods_data['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
            $goods_data['goods_price'] = $goods_data['retail_goods_price'];
            $goods_data['return_credit'] = $val['return_credit'];
            $goods_data['goods_stock'] = $val['goods_stock'];
            $goods_data['goods_type_name'] = GoodsTypeModel::selectValue('id',$goods_data['goods_type']);
            $data[$key] = $goods_data;
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }

    /**
     * Get a JWT via given credentials.
     *  上货商品列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function LoadingGoodsListing(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $goods_list = GoodsModel::where(['status'=>1,'network_id'=>$user_data['id']])->orderBy('goods_sales','desc')->skip(($page - 1) * $take)->take($take)->get();

        foreach($goods_list as $key=>$val){
            $goods_list[$key]['goods_cover'] = env('OSS_URL').$val['goods_cover'];
            $goods_list[$key]['goods_type_name'] = GoodsTypeModel::selectValue('id',$val['goods_type']);
            $network_goods = NetworkGoodsModel::where(['network_id'=>$user_data['id'],'goods_id'=>$val['id']])->select(['return_credit'])->first();
            $goods_list[$key]['return_credit'] = isset($network_goods['return_credit'])?$network_goods['return_credit']:0;
            $goods_list[$key]['goods_price'] = $val['retail_goods_price'];
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$goods_list]);

    }


    /**
     * Get a JWT via given credentials.
     *  上货生成订单
     * @return \Illuminate\Http\JsonResponse
     */
    public function LoadingGoodsAdd(Request $request)
    {
        
        Log::info($request->input());

        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $goods_list = $request->post('goods_list');
        if(empty($goods_list)){
            return response()->json(['code' => '201', 'msg' => '请选择上货商品']);
        }
        $goods_list_data = json_decode($goods_list,true);

        $orderSn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

        $network_goods_order = array();
        //商品总价
        $goods_total_amount = 0;
        //商品抵扣数
        $credit_deduction = 0;
        //商品抵扣金额
        $credit_deduction_amount = 0;
        //桶押金
        $total_barrel_deposit = 0;
        //桶押金抵扣
        $total_barrel_deposit_deduction = 0;
        //桶押金抵扣数
        $total_barrel_deposit_deduction_number = 0;
        //配送费抵扣
        $distribution_fee_deduction = 0;

        foreach($goods_list_data as $key=>$val){
            $goods_data = GoodsModel::where(['status'=>1,'id'=>$val['goods_id']])->first();
            if(empty($goods_data)){
                return response()->json(['code' => '201', 'msg' => $val['goods_title']."已下架或库存不足"]);
            }

            $goods_data_arrar[] = $goods_data;
            //桶押金
            $detail_barrel_deposit = $val['number']*$goods_data['barrel_deposit'];

            $network_goods = NetworkGoodsModel::where(['network_id'=>$user_data['id'],'goods_id'=>$val['goods_id']])->select(['return_credit','barrel_deposit'])->first();
            //商品抵扣数
            if(isset($network_goods['return_credit']) && $network_goods['return_credit']>$val['number']){
                $return_credit = $val['number'];
            }else{
                if(isset($network_goods['return_credit'])){
                    $return_credit = $network_goods['return_credit'];
                }else{
                    $return_credit = 0;
                }
            }

            //扣除商品信用
            if($return_credit>0){
                NetworkGoodsModel::where(['network_id'=>$user_data['id'],'goods_id'=>$val['goods_id']])->decrement('return_credit',$return_credit);
                NetworkCreditRecordModel::insert([
                    'network_id' => $user_data['id'],
                    'goods_id'=> $val['goods_id'],
                    'number' => $return_credit,
                    'amount' => $return_credit*$goods_data['retail_goods_price'],
                    'remark' => '上货信用抵扣',
                    'status' => 0,
                    'relation_data' => $orderSn,
                    'type' => 1,
                    'created_at' => date('Y-m-d H:i:s',time())
                ]);
            }
           
            //桶押金抵扣数
            if(!empty($network_goods)){
                if($network_goods['barrel_deposit']>$val['number']){
                    $barrel_deposit_number = $val['number'];
                }else{
                    $barrel_deposit_number = $network_goods['barrel_deposit'];
                }
            }else{
                $barrel_deposit_number = 0;
            }
         
            //扣除桶押金
            if($barrel_deposit_number>0){
                NetworkGoodsModel::where(['network_id'=>$user_data['id'],'goods_id'=>$val['goods_id']])->decrement('barrel_deposit',$barrel_deposit_number);
                NetworkCreditRecordModel::insert([
                    'network_id' => $user_data['id'],
                    'goods_id'=> $val['goods_id'],
                    'number' => $barrel_deposit_number,
                    'amount' => $barrel_deposit_number*$goods_data['barrel_deposit'],
                    'remark' => '上货桶押金抵扣',
                    'status' => 0,
                    'relation_data' => $orderSn,
                    'type' => 5,
                    'created_at' => date('Y-m-d H:i:s',time())
                ]);
            }

            $network_goods_order[$key] = [
                'order_sn' => $orderSn,
                'network_id' => $user_data['id'],
                'goods_id' => $val['goods_id'],
                'goods_title' => $val['goods_title'],
                'goods_price' => $goods_data['retail_goods_price'],
                'number' => $val['number'],
                'goods_total_amount' => $val['number']*$goods_data['retail_goods_price'],
                'credit_deduction' => $return_credit,
                'credit_deduction_amount' => $return_credit*$goods_data['retail_goods_price'],
                'barrel_deposit' => $detail_barrel_deposit,
                'barrel_deposit_number' => $barrel_deposit_number,
                'barrel_deposit_deduction' => $barrel_deposit_number*$goods_data['barrel_deposit'],
                'created_at' => date('Y-m-d H:i:s',time())
            ];

            //商品抵扣数
            $credit_deduction = $credit_deduction+$return_credit;
            //商品抵扣金额
            $credit_deduction_amount = $credit_deduction_amount+$return_credit*$goods_data['retail_goods_price'];
            //桶押金抵扣数
            $total_barrel_deposit_deduction_number = $total_barrel_deposit_deduction_number+$barrel_deposit_number;
            //桶押金抵扣金额
            $total_barrel_deposit_deduction = $total_barrel_deposit_deduction+$barrel_deposit_number*$goods_data['barrel_deposit'];
            //桶总押金
            $total_barrel_deposit = $total_barrel_deposit+$val['number']*$goods_data['barrel_deposit'];
            //商品总价
            $goods_total_amount = $goods_total_amount+$goods_data['retail_goods_price']*$val['number'];

        }
        //总价
        $total_amount = $goods_total_amount+$total_barrel_deposit;
        //商品抵扣后金额
        $amount = $total_amount-$credit_deduction_amount-$total_barrel_deposit_deduction;

        $distribution_price = 0;

        //计算减去配送费后实际需要支付
        if($user_data['distribution_price']>0 && $amount>0){
            if($amount>$user_data['distribution_price']){
                $amount = $amount-$user_data['distribution_price'];
                $distribution_price = $user_data['distribution_price'];
            }else{
                $distribution_price = $amount;
                $amount = 0;
            }
            //扣除配送费
            AdminUserModel::where(['openid' => $openid])->decrement('distribution_price',$distribution_price);
            NetworkCreditRecordModel::insert([
                'network_id' => $user_data['id'],
                'amount' => $distribution_price,
                'remark' => '上货配送费抵扣',
                'status' => 0,
                'relation_data' => $orderSn,
                'type' => 3,
                'created_at' => date('Y-m-d H:i:s',time())
            ]);
        }

        //添加订单
        NetworkGoodsOrderModel::insert([
            'order_sn' => $orderSn,
            'network_id' => $user_data['id'],
            'openid' => $openid,
            'goods_list' => $goods_list,
            'total_amount' => $total_amount,
            'credit_deduction' => $credit_deduction,
            'credit_deduction_amount' => $credit_deduction_amount,
            'barrel_deposit' => $total_barrel_deposit,
            'barrel_deposit_deduction' => $total_barrel_deposit_deduction,
            'barrel_deposit_deduction_number' => $total_barrel_deposit_deduction_number,
            'distribution_fee_deduction'=> $distribution_price,
            'amount' => $amount,
            'goods_total_amount' => $goods_total_amount,
            'created_at' => date('Y-m-d H:i:s',time())
        ]);
        //添加订单详情
        NetworkGoodsOrderDetailModel::insert($network_goods_order);

        $data['order_sn'] = $orderSn;

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);

    }


    /**
     * Get a JWT via given credentials.
     *  上货订单详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function LoadingOrderDetail(Request $request)
    {
        $openid = $request->post('openid');

        $user_data = AdminUserModel::where(['openid' => $openid])->first();

        if (empty($user_data) || empty($openid)) {
            return response()->json(['code' => '401', 'msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');
        if(empty($order_sn)){
            return response()->json(['code' => '201', 'msg' => '订单号不能为空']);
        }

        $order_data = NetworkGoodsOrderModel::where(['order_sn'=>$order_sn])->first();

        if(empty($order_sn)){
            return response()->json(['code' => '201', 'msg' => '订单不存在']);
        }

        $order_detail = NetworkGoodsOrderDetailModel::where(['order_sn'=>$order_sn])->get();

        foreach ($order_detail as $key=>$val){
            $order_detail[$key]['stay_pay_number'] = $val['number']-$val['credit_deduction'];
            $order_detail[$key]['stay_pay'] = ($val['number']-$val['credit_deduction'])*$val['goods_price'];
        }

        $order_data['order_detail'] = $order_detail;
        $order_data['audit_reason']  = $order_data['remark'];

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$order_data]);

    }

    /**
     * Get a JWT via given credentials.
     *  下单支付
     * @return \Illuminate\Http\JsonResponse
     */
    public function LoadingOrderPay(Request $request){

        $openid = $request->post('openid');
        $user_data = AdminUserModel::where(['openid'=>$openid])->first();
        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');

        $order_data = NetworkGoodsOrderModel::where(['order_sn'=>$order_sn])->first();
        if(empty($order_data) || $order_data['status']>0){
            return response()->json(['code'=>'203','msg' => '该订单已支付']);
        }

        try {
            if(!empty($order_data['pay_time'])){
                $minute=floor((time()-strtotime($order_data['pay_time']))%86400/60);
                if($minute<15){
                    $config = json_decode($order_data['pay_sigin']);
                }

                return response()->json(['code'=>'200','msg' => '请求成功','data'=>$config]);

            }else{
                if($order_data['amount'] <= 0){
                    NetworkGoodsOrderModel::where(['order_sn'=>$order_data['order_sn']])->update([
                        'status' => 1,
                        'pay_time'=>date('Y-m-d H:i:s',time())
                    ]);
                    return response()->json(['code'=>'200','msg' => '请求成功','data'=>array()]);

                }else{
                    $config = NetworkGoodsOrderModel::payByWeChat($order_data['order_sn'],$user_data['openids'],$order_data['amount']);

                    NetworkGoodsOrderModel::where(['order_sn'=>$order_data['order_sn']])->update([
                        'pay_sigin' => json_encode($config),
                        'pay_time'=>date('Y-m-d H:i:s',time())
                    ]);
                    return response()->json(['code'=>'200','msg' => '请求成功','data'=>$config]);

                }
            }


        } catch (\Exception $e) {
            return response()->json(['code'=>'404','msg' => '请求成功','data'=>$e->getMessage()]);
        }


    }


    /**
     * Get a JWT via given credentials.
     *  下单支付回调
     * @return \Illuminate\Http\JsonResponse
     */
    public function LoadingOrderNotify(Request $request){

        $payment = Factory::payment(NetworkGoodsOrderModel::getConfig());

        $response = $payment->handlePaidNotify(function ($message, $fail) {


            $order_data = NetworkGoodsOrderModel::where(['order_sn'=>$message['out_trade_no']])->first();
            if(empty($order_data) || $order_data['status']>0){
                return true;
            }

            if ($message['return_code'] === 'SUCCESS') {
                //开启事务
                DB::beginTransaction();

                NetworkGoodsOrderModel::where(['order_sn'=>$message['out_trade_no']])->update([
                    'status' => 1,
                    'transaction_id' => $message['transaction_id'],
                    'pay_time'=>date('Y-m-d H:i:s',time())
                ]);

                Db::commit();

                return true;

            } else {
                return $fail('通信失败，请稍后再通知我');
            }
        });
    }


}
